package com.example.educationcommunity.controller;

import com.example.educationcommunity.dto.PagingDTO;
import com.example.educationcommunity.dto.QuestionDTO;
import com.example.educationcommunity.mapper.QuestionMapper;
import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.Question;
import com.example.educationcommunity.model.QuestionExample;
import com.example.educationcommunity.model.User;
import com.example.educationcommunity.service.CommentService;
import com.example.educationcommunity.service.QuestionService;
import org.h2.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommentService commentService;

    @RequestMapping("/")
    public String index(Model model,
                        @RequestParam(name="page",defaultValue = "1") Integer page,
                        @RequestParam(name = "size",defaultValue = "7") Integer size,
                        @RequestParam(name ="search",required = false) String search){

        List<QuestionDTO> top = new ArrayList<>();
        List<Question> tops =new ArrayList<>();

        if(!StringUtils.isNullOrEmpty(search)){
            PagingDTO pagination= questionService.list(page,size,search);
            model.addAttribute("pagination",pagination);
            return "index";
        }else {
            QuestionExample example = new QuestionExample();
            example.createCriteria()
                    .andIsTopEqualTo(true);
            tops = questionMapper.selectByExampleWithBLOBs(example);
            PagingDTO pagination= questionService.list(page,size);
            model.addAttribute("pagination",pagination);
        }
        for (Question question : tops) {
            QuestionDTO questionDTO = new QuestionDTO();
            User user = userMapper.selectByPrimaryKey(question.getCreator());
            BeanUtils.copyProperties(question, questionDTO);
            questionDTO.setUser(user);
            questionDTO.setCommentCount(commentService.countByParentId(question.getId()));
            top.add(questionDTO);
        }
        model.addAttribute("tops",top);
        return "index";
    }


}
